/*
   Copyright 2022 cmanlh

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/**
 * number input, support number formatting display
 * 
 */
import JscConfig from './config.js';
import JscConstant from './constant.js';
import JscDatabind from './databind.js';
import JscFormatter from './formatter.js';
export default class JscInputNumber extends JscDatabind {
    static get observedAttributes() { return ['max', 'min', 'required', 'readonly', 'disabled', 'placeholder', 'value', 'jscbind', 'suffix', 'suffixcolor', 'times'] }
    static #suffixCache = new Map();

    #thousandsSep = ',';
    #value;
    #formatted;
    #isInputting;
    #isProcessing;;
    #input = undefined;
    #isShiftKey;
    #max = null;
    #min = null;
    #required = false;
    #decimals = 0;
    #jscBind = null;
    #times = null;

    constructor() {
        super();
        this.#init();
        this.#render();
    }

    connectedCallback() {
        this.#bindEventForInput();
    }

    attributeChangedCallback(name, oldValue, newValue) {
        switch (name) {
            case 'value': {
                if (oldValue != newValue) {
                    this.value = newValue;
                }
                break;
            }
            case 'readonly': {
                if (oldValue != newValue) {
                    if (newValue || '' == newValue) {
                        this.#input.setAttribute('readonly', true);
                    } else {
                        this.#input.removeAttribute('readonly');
                    }
                }
                break;
            }
            case 'disabled': {
                if (oldValue != newValue) {
                    if (newValue || '' == newValue) {
                        this.#input.setAttribute('disabled', true);
                    } else {
                        this.#input.removeAttribute('disabled');
                    }
                }
                break;
            }
            case 'jscbind': {
                if (oldValue != newValue) {
                    this.#jscBind = newValue;
                }
                break;
            }
        }
    }

    bindRefresh(bindStamp) {
        if (super.bindRefresh(bindStamp)) {
            if (null != this.bind && null != this.#jscBind) {
                this.#value = this.fetchBindValue(this.#jscBind);
                this.#renderInput();
            }
        }
    }

    set value(val) {
        let input = this.#input;
        if (this.#value == val && this.#formatted == input.value) {
            return;
        }
        this.#value = val;
        this.updateBindValue(this.#jscBind, this.#value);
        this.#renderInput();
    }

    get value() {
        return this.#value;
    }

    #init() {
        let max = this.getAttribute('max');
        if (max) {
            this.#max = Number.parseFloat(max);
        }

        let min = this.getAttribute('min');
        if (min) {
            this.#min = Number.parseFloat(min);
        }

        let decimals = this.getAttribute('decimals');
        if (decimals) {
            this.#decimals = Number.parseInt(decimals);
        }

        let required = this.getAttribute('required');
        if (null == required) {
            this.#required = true;
        }

        this.#jscBind = this.getAttribute('jscbind');
        this.#times = this.getAttribute('times');
    }

    #render() {
        const shadowRoot = this.attachShadow({ mode: 'open' });
        shadowRoot.innerHTML = `
        <link rel='stylesheet' type='text/css' href='${JscConfig.cssUrl}'/>
        <input type='text' class='inputNumber'>
        `;
        this.#input = this.shadowRoot.querySelector('input');
        this.#renderSuffix(this.#input);

        if (this.getAttribute('placeholder')) {
            this.#input.setAttribute('placeholder', this.getAttribute('placeholder'));
        }

        if (this.getAttribute('readonly')) {
            this.#input.setAttribute('readonly', true);
        }

        if (this.getAttribute('disabled')) {
            this.#input.setAttribute('disabled', true);
        }
    }

    #renderSuffix(el) {
        let suffix = this.getAttribute('suffix');
        if (null == suffix) {
            return;
        }

        suffix = suffix.trim();
        if (0 == suffix.length) {
            return;
        }

        let suffixPng = JscInputNumber.#suffixCache.get(suffix);
        if (null == suffixPng) {
            let inputStyle = window.getComputedStyle(el);
            let size = parseInt(inputStyle.fontSize);

            let suffixCanvas = document.createElement('canvas');
            suffixCanvas.width = size * suffix.length + 6;
            suffixCanvas.height = size + 2;

            let cxt = suffixCanvas.getContext('2d');
            cxt.fillStyle = this.getAttribute('suffixcolor') || inputStyle.color;
            cxt.font = inputStyle.fontWeight + ' ' + size + 'px ' + inputStyle.fontFamily;
            cxt.textBaseline = 'top';
            cxt.fillText(suffix, 2, 2);
            suffixPng = {
                png: suffixCanvas.toDataURL('image/png', 1.0),
                width: suffixCanvas.width
            }

            JscInputNumber.#suffixCache.set(suffix, suffixPng);
        }

        el.style.backgroundImage = 'url(' + suffixPng.png + ')';
        el.style.backgroundSize = 'auto';
        el.style.backgroundPosition = 'right center';
        el.style.backgroundRepeat = 'no-repeat';
        el.style.paddingRight = suffixPng.width + 'px';
        el.style.boxSizing = 'border-box';
    }

    #renderInput() {
        let displayValue = this.#value;
        if (null != this.#times) {
            displayValue = this.#value / this.#times;
        }
        this.#formatted = this.#input.value = JscFormatter.number(displayValue, {
            decimals: this.#decimals,
            thousandsSep: this.#thousandsSep,
            toRound: false
        });
        this.setAttribute('value', this.#value);
    }

    #bindEventForInput() {
        let input = this.#input;
        let self = this;
        input.addEventListener('keyup', function (e) {
            self.#isShiftKey = false;
            switch (e.code) {
                case JscConstant.KeyCode.DELETE:
                case JscConstant.KeyCode.BACKSPACE:
                    if (self.#formatted.indexOf('.') != -1 && input.value.indexOf('.') == -1) {
                        input.value = input.value.substr(0, input.selectionStart);
                    }
                    break;
                case JscConstant.KeyCode.TAB: {
                    return;
                }
                case JscConstant.KeyCode.SHIFT_RIGHT:
                case JscConstant.KeyCode.SHIFT_LEFT: {
                    self.#isShiftKey = true;
                    break;
                }
                case JscConstant.KeyCode.LEFT:
                case JscConstant.KeyCode.RIGHT:
                    return;
            }

            if (self.#formatted == input.value) {
                return;
            }

            if (self.#isProcessing) {
                e.preventDefault();
                return;
            }

            if (!self.#isInputting) {
                self.#isInputting = true;
            }

            let result = self.#parseInputValue();
            if (null !== self.#times) {
                self.value = result.value * self.#times;
            } else {
                self.value = result.value;
            }
            self.#correctCursorPosition(result);
            self.#isValidity(result.value)
        });

        input.addEventListener('paste', function (e) {
            setTimeout(function () {
                let result = self.#parseInputValue();
                if (null !== self.#times) {
                    self.value = result.value * self.#times;
                } else {
                    self.value = result.value;
                }
                self.#correctCursorPosition(result);
                self.#isValidity(result.value)
            }, 10)
        });

        input.addEventListener('input', function (e) {
            if (!self.#isShiftKey) {
                return;
            }

            let result = self.#parseInputValue();
            if (null !== self.#times) {
                self.value = result.value * self.#times;
            } else {
                self.value = result.value;
            }
            self.#correctCursorPosition(result);
            self.#isValidity(result.value)
        });
    }

    #parseInputValue() {
        let result = {
            value: '',
            cursorPosition: null
        };
        this.#isProcessing = true;
        let input = this.#input;
        let newLength = input.value.length;
        if (newLength > 0) {
            let newValue = '';
            var cursorPosition = input.selectionStart, updatedCursorPosition = 0;
            var keepDeciaml = 0;
            var duplicatePoint = false;
            for (var i = 0; i < newLength; i++) {
                var charCode = input.value.charCodeAt(i);
                if (charCode === 45 && i === 0) {
                    newValue = newValue.concat('-');
                    if (i < cursorPosition) {
                        updatedCursorPosition++;
                    }
                    continue;
                }
                if (charCode > 47 && charCode < 58) {
                    if (duplicatePoint) {
                        if (keepDeciaml < this.#decimals) {
                            keepDeciaml++;
                        } else {
                            break;
                        }
                    }
                    newValue = newValue.concat(input.value.charAt(i));

                    if (i < cursorPosition) {
                        updatedCursorPosition++;
                    }
                } else if (46 == charCode || 12290 == charCode || 65294 == charCode) {
                    if (duplicatePoint) {
                        break;
                    }
                    newValue = newValue.concat('.');
                    duplicatePoint = true;
                    if (i < cursorPosition) {
                        updatedCursorPosition++;
                    }
                } else if (charCode > 65295 && charCode < 65306) {
                    if (duplicatePoint) {
                        if (keepDeciaml < this.#decimals) {
                            keepDeciaml++;
                        } else {
                            break;
                        }
                    }
                    newValue = newValue.concat(String.fromCharCode(charCode - 65248));

                    if (i < cursorPosition) {
                        updatedCursorPosition++;
                    }
                } else if (0 == i && (45 == charCode || 65293 == charCode)) {
                    newValue = newValue.concat('-');

                    if (i < cursorPosition) {
                        updatedCursorPosition++;
                    }
                }
            }
            result.value = newValue;
            result.cursorPosition = updatedCursorPosition;
        }

        this.#isProcessing = false;
        this.#isInputting = false;

        return result;
    }

    #correctCursorPosition(valueInfo) {
        if (null != valueInfo.value && '' != valueInfo.value) {
            let cursorPosition = valueInfo.cursorPosition;
            if (valueInfo.value.indexOf('.') == valueInfo.cursorPosition) {
                cursorPosition = this.#formatted.indexOf('.');
            } else {
                for (var i = 0, positionCounter = 0; positionCounter < valueInfo.cursorPosition; i++) {
                    if (this.#formatted.charCodeAt(i) == 44) {
                        cursorPosition++;
                    } else {
                        positionCounter++;
                    }
                }
            }
            this.#input.setSelectionRange(cursorPosition, cursorPosition);
        }
    }

    checkValidity() {
        if (null != this.#times) {
            return this.#isValidity(this.#value / this.#times);
        } else {
            return this.#isValidity(this.#value);
        }
    }

    #isValidity(val) {
        let input = this.#input;
        let errMsg = '';
        if (this.#required && (undefined == val || '' == val)) {
            errMsg = '该字段不能为空';
        } else {
            let currentVal = Number.parseFloat(val);
            if (this.#max && currentVal > this.#max) {
                errMsg = '最大允许输入'.concat(this.#max);
            } else if (this.#min && currentVal < this.#min) {
                errMsg = '最小允许输入'.concat(this.#min);
            }
        }

        input.setCustomValidity(errMsg);
        input.reportValidity();

        if ('' === errMsg) {
            return true;
        } else {
            return false;
        }
    }
}

if (!customElements.get('jsc-input-number')) {
    window.customElements.define("jsc-input-number", JscInputNumber);
}